const ListingPrisma = require('../models/ListingPrisma');
const { prisma } = require('../config/prisma');

async function triggerAutoPublish() {
  console.log('=== 手动触发自动发布 ===\n');

  try {
    const now = new Date();
    console.log(`当前时间: ${now.toLocaleString('zh-CN')}`);

    // 1. 查询应该被自动发布的信息
    const expiredListings = await prisma.listings.findMany({
      where: {
        audit_status: 'PENDING',
        audit_admin_id: null,
        audit_time: null,
        NOT: {
          audit_comment: 'USER_OFFLINE'
        },
        OR: [
          {
            auto_publish_at: {
              lte: now,
              not: null
            }
          },
          {
            auto_publish_at: null,
            created_at: {
              lte: new Date(now.getTime() - 30 * 60 * 1000)
            }
          }
        ]
      },
      select: {
        id: true,
        company_name: true,
        created_at: true,
        auto_publish_at: true
      }
    });

    console.log(`\n找到 ${expiredListings.length} 条需要自动发布的信息:\n`);

    if (expiredListings.length > 0) {
      expiredListings.forEach((listing, index) => {
        console.log(`${index + 1}. ID:${listing.id} - ${listing.company_name || '(无名称)'}`);
        console.log(`   创建时间: ${listing.created_at.toLocaleString('zh-CN')}`);
        if (listing.auto_publish_at) {
          console.log(`   自动发布时间: ${listing.auto_publish_at.toLocaleString('zh-CN')}`);
          const overdue = Math.floor((now - listing.auto_publish_at) / 1000 / 60);
          console.log(`   已超时: ${overdue} 分钟`);
        }
        console.log();
      });

      // 2. 执行自动发布
      console.log('执行自动发布...\n');
      const count = await ListingPrisma.autoPublishExpired();
      console.log(`✅ 成功自动发布 ${count} 条挂牌信息`);

      // 3. 验证结果
      if (count > 0) {
        console.log('\n验证发布结果:');
        for (const listing of expiredListings) {
          const updated = await prisma.listings.findUnique({
            where: { id: listing.id },
            select: {
              id: true,
              company_name: true,
              audit_status: true,
              status: true,
              audit_time: true,
              audit_comment: true,
              auto_publish_at: true
            }
          });

          if (updated) {
            console.log(`\nID:${updated.id} - ${updated.company_name || '(无名称)'}`);
            console.log(`  审核状态: ${updated.audit_status}`);
            console.log(`  上架状态: ${updated.status}`);
            console.log(`  审核时间: ${updated.audit_time?.toLocaleString('zh-CN')}`);
            console.log(`  审核备注: ${updated.audit_comment}`);
            console.log(`  auto_publish_at: ${updated.auto_publish_at || 'null (已清除)'}`);
          }
        }
      }
    } else {
      console.log('没有需要自动发布的信息');
    }

  } catch (error) {
    console.error('❌ 自动发布失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

triggerAutoPublish();
